<?php

namespace App\Console\Commands\PolicyUpload;

use App\Models\PolicyUpload;
use App\Repositories\Contracts\PlatformInterface;
use App\Services\PolicyUpload\CtripService;
use App\Services\PolicyUpload\QnService;
use App\Services\PolicyUpload\RuleService;
use App\Services\PolicyUpload\TcService;
use Curl\CurlService\CurlService;
use Curl\StrService\StrService;
use MakeRep\Repository;

class PolicyUploadService
{


    private $ctripPolicy = [];              //恒博携程
    private $mhCtripPolicy = [];            //茂华携程
    private $ctripRulePolicy = [];          //恒博规则运价
    private $mhCtripRulePolicy = [];          //茂华规则运价
    private $qnPolicy = [];                 //去哪

    private $qnFxPolicy = [];               //去哪分销

    private $tcPolicy = [];                 //同程
    private $fzPolicy = [];                 //飞猪
    private $fzCommonPolicy = [];           //飞猪普政
    private $mtPolicy = [];                 //美团


    /**
     * 政策上传
     * @param $data
     * @param $policy
     * @return true
     * @throws \Exception
     */
    public function uploadPolicy($data,$policy)
    {

        try {

            foreach ($policy as $key=>$value) {

                /**
                 * 规则有效期
                 */

                if (!empty($value['rule_at']) && ($value['rule_at'] > date('Y-m-d') || $value['rule_end'] <  date('Y-m-d'))) {

                    continue;
                }

                foreach ($data as $flight) {

                    /**
                     * 数据源是否正确
                     */

                    if ($value['source_id'] != $flight['source_id'] ) {

                        continue;
                    }

                    /**
                     * 是否是航司
                     */
                    if ($value['airline'] && !strpos(' '.$value['airline'],$flight['hs_code'])) {

                        continue;
                    }

                    /**
                     * 判断起飞机场
                     */

                    if ($value['depart'] && !strpos(' '.$value['depart'],$flight['depart_city_code'])){
                        continue;
                    }

                    /**
                     * 判断到达机场
                     */

                    if ($value['arrive'] && !strpos(' '.$value['arrive'],$flight['arrived_city_code'])){
                        continue;
                    }


                    /**
                     * 起飞时间
                     */

                    if (!empty($value['depart_at']) && ($value['depart_at'] > $flight['date'] || $value['depart_end'] < $flight['date'])) {

                        continue;
                    }

                    /**
                     * 不适合的航线则继续
                     */
                    if ($value['flight_lines'] && !strpos(' '.$value['flight_lines'],$flight['depart_city_code'].$flight['arrived_city_code'])) {

                        continue;
                    }

                    $cabinMinPrice = 0;
                    $cabinMin = [];

                    foreach ($flight['cabins'] as $cabin) {

                        /**
                         * 不适合舱位继续
                         */
                        if ($value['cabins'] && !strpos(' ' . $value['cabins'], $cabin['cabin_code'])) {

                            continue;
                        }

                        /**
                         * 产品类型判断
                         */
                        //$cabinName = explode(':', $cabin['source_type']);

                        if ($value['source_type'] != '0'/* && !strpos(' ' .  $cabin['source_type'], $value['source_type']) */) {

                            $isSourceTypeContinue = false;

                            $policySourceType = explode(',', $value['source_type']);
                            foreach ($policySourceType as $sourceType) {
                                if (strpos(' ' .  $cabin['source_type'], $sourceType)) {
                                    $isSourceTypeContinue = true;
                                    break;
                                }
                            }

                            //如果不能继续，返回
                            if (!$isSourceTypeContinue) {

                                continue;
                            }

                        }

                        /**
                         * 判断最小座位数
                         */
                        if ($value['seat_min'] && $value['seat_min'] > $cabin['seat']) {

                            continue;
                        }

                        if ($value['seat_max'] && $value['seat_max'] < $cabin['seat']) {

                            continue;
                        }

                        /**
                         * 查找最低价格
                         */
                        if ($cabinMinPrice == 0 || $cabinMinPrice > $cabin['price']) {

                            $cabinMin = $cabin;
                        }
                    }

                    if ($cabinMin) {

                        /**
                         * 上传政策
                         */

                        //政策不存在则上传
                        $policyExist = $this->policyExist($flight,$cabinMin,$value);

                        if (!$policyExist) {

                            /**
                             * 检查是否有差价
                             */
                            $diffPrice = 0;
                            if (!empty($value['diff_price'])) {
                                $diffPrice = $this->diffPrice($flight,$cabinMin,$value);
                                if ($diffPrice <= 0) {

                                    //差价不可用删除政策
                                    $this->policyDelete($flight,$value);
                                    continue;
                                }
                            }

                            $uploadRes = $this->saveUploadPolicy($flight,$cabinMin,$value);
                            if ($uploadRes) {

                                switch ($value['product_type']) {

                                    //携程包机
                                    case 10: {

                                        //上传携程包机
                                        $flight['ctrip_type']   = 1;              //携程区分
                                        $flight['product_type'] = 'BJ';         //产品类型
                                        $this->ctripPolicy[] = $this->ctripUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    //携程包机
                                    case 11: {

                                        //上传携程包机
                                        $flight['ctrip_type']   = 2;
                                        $flight['product_type'] = 'BJ';         //产品类型

                                        $this->mhCtripPolicy[] = $this->ctripUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    //携程规则运价
                                    case 20: {

                                        //规则运价
                                        $this->ctripRulePolicy[] = $this->ctripRuleUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    //携程规则运价
                                    case 21: {

                                        //规则运价
                                        $this->mhCtripRulePolicy[] = $this->ctripRuleUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    case 30: {

                                        //上传携程包机
                                        $this->qnPolicy[]  = $this->quUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice,'STOCK');
                                        break;
                                    }
                                    case 31: {

                                        //上传携程包机
                                        $this->qnPolicy[]  = $this->quUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    case 36:{

                                        //上传携程包机
                                        $this->qnFxPolicy[]  = $this->quUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    case 40: {
                                        $this->tcPolicy[]  = $this->tcUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }
                                    case 50:
                                    case 51:{

                                        $this->fzPolicy[]  = $this->fzUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }
                                    case 52: {

                                        $this->fzCommonPolicy[]  = $this->fzUploadCommon($flight,$cabinMin,$value,$uploadRes,$diffPrice);
                                        break;
                                    }

                                    case 60: {

                                        $this->mtPolicy[]  = $this->mtUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice);

                                        break;
                                    }
                                    case 61: {

                                        $this->mtPolicy[]  = $this->mtUpload($flight,$cabinMin,$value,$uploadRes,$diffPrice,'COMMON');

                                        break;
                                    }
                                }
                            }
                        }
                    } else {

                        //如果产品不存在删除政策，数据量大删除不了
                        $this->policyDelete($flight,$value);
                    }
                }

            }

        } catch (\Exception $exception) {

            logger('自动上传政策失败'.$exception->getMessage());
        }

        return true;
    }

    /**
     * 统一上传所有平台
     * @return string|void
     */
    public function otaUploadPolicy(){



        $hbCtripRes = true;
        $mhCtripRes = true;
        $quRes = true;
        $tcRes = true;
        $fzRes = true;
        $mtRes = true;

        try {

            /**
             * 恒博携程上传政策
             */
            if ($this->ctripPolicy) {

                $hbCtripRes = $this->ctripUploadPolicy($this->ctripPolicy);
            }
        } catch (\Exception $exception) {

        }

        try {

            /**
             * 茂华携程上传政策
             */
            if ($this->mhCtripPolicy) {

                $mhCtripRes = $this->mhCtripUploadPolicy($this->mhCtripPolicy);
            }
        } catch (\Exception $exception) {


        }


        try {

            /**
             * 携程规则运价
             */
            if ($this->ctripRulePolicy) {

                $criptRuleInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\CtripRulePolicyInterface');
                $res = $criptRuleInterface->add($this->ctripRulePolicy);

                if (isset($res['TradeResult']) && isset($res['TradeResult']['Result']) && !empty($res['TradeResult']['Result']['SuccessList'])) {


                    /*$rulePolicyData = [
                        'admin_id'              => $policy['admin_id'],
                        'policy_id'             => $res['TradeResult']['Result']['SuccessList'][0],
                        'policy_code'           => $item['PolicyCode'],
                        'platform'              => 20,
                        'airline'               => $item['AirLine'],
                        'way'                   => $item['FlightWay'] == 'S' ? 1 : 2,
                        'flight_date'           => $item['GoEffectDate'].'/'.$item['GoExpiryDate'],
                        'sale_date'             => $item['SaleEffectDate'].'/'.$item['SaleExpiryDate'],
                        'commision'             => $item['RulePriceList'][0]['Commision'],
                        'cabin'                 => $item['RulePriceList'][0]['SubClass'],
                        'status'                => isset($item['PolicyStatus']) && $item['PolicyStatus'] == 'NORMAL' ? 1 : 0,
                    ];


                    $rulePolicyInterface = resolve('App\Repositories\Contracts\RulePolicyInterface');
                    $rulePolicyInterface->add($rulePolicyData);*/

                } else {
                    logger('恒博规则运价上传失败原因:'.$res);
                }


            }
        }catch (\Exception $exception) {


        }

        try {

            /**
             * 茂华携程规则运价
             */
            if ($this->mhCtripRulePolicy) {

                $criptRuleInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\CtripRulePolicyInterface');
                $res = $criptRuleInterface->addMh($this->mhCtripRulePolicy);

                if (isset($res['TradeResult']) && isset($res['TradeResult']['Result']) && !empty($res['TradeResult']['Result']['SuccessList'])) {


                } else {
                    logger('JD订单茂华平台上传失败原因:'.$res);
                }


            }
        }catch (\Exception $exception) {


        }

        try {

            /**
             * 上传同程
             */
            if ($this->tcPolicy) {

                $tcRes = $this->tcUploadPolicy($this->tcPolicy);

            }
        }catch (\Exception $exception) {


        }


        try {

            /**
             * 上传去哪
             */
            if ($this->qnPolicy) {

                $quRes = $this->qnUploadPolicy($this->qnPolicy);
                if ($quRes) {

                    $this->qnPolicy         = [];

                }
            }


        }catch (\Exception $exception) {


        }

        try {

            /**
             * 上传去哪
             */
            if ($this->qnFxPolicy) {

                $quRes = $this->qnFxUploadPolicy($this->qnFxPolicy);
                if ($quRes) {

                    $this->qnFxPolicy         = [];

                }
            }


        }catch (\Exception $exception) {


        }

        try {

            /**
             * 飞猪上传政策
             */
            if ($this->fzPolicy) {

                $res = CurlService::post(env('JAVA_HB_GATEWAY').'/booking/fliggyPolicy/addSpecialPolicy',['policyList'=>$this->fzPolicy,'policyType'=>$this->fzPolicy[0]['policyType']]);

                if (!($res && isset($res['code']) && $res['code'] === 0)) {

                    $fzRes = false;
                    logger($this->fzPolicy[0]['policyCode'].'飞猪平台上传失败:'.json_encode($this->fzPolicy,JSON_UNESCAPED_UNICODE));
                    logger($this->fzPolicy[0]['policyCode'].'飞猪平台上传原因:'.json_encode($res,JSON_UNESCAPED_UNICODE));
                } else {

                    $this->fzPolicy         = [];
                }

            }
        }catch (\Exception $exception) {


        }

        try {

            /**
             * 飞猪上传政策
             */
            if ($this->fzCommonPolicy) {
                $res = CurlService::post(env('JAVA_HB_GATEWAY').'/booking/fliggyPolicy/addPolicy',['policyList'=>$this->fzCommonPolicy,'policyType'=>$this->fzCommonPolicy[0]['policyType']]);
                if (!($res && isset($res['code']) && $res['code'] === 0)) {

                    $fzRes = false;
                    logger($this->fzPolicy[0]['policyCode'].'飞猪普政平台上传失败:'.json_encode($this->fzCommonPolicy,JSON_UNESCAPED_UNICODE));
                    logger($this->fzPolicy[0]['policyCode'].'飞猪普政平台上传原因:'.json_encode($res,JSON_UNESCAPED_UNICODE));
                } else {

                    $this->fzCommonPolicy   = [];
                }

            }
        }catch (\Exception $exception) {


        }

        try {

            /**
             * 飞猪上传政策
             */
            if ($this->mtPolicy) {


                $res = CurlService::post(env('JAVA_HB_GATEWAY').'/booking/meiTuanPolicy/add',['policy'=>$this->mtPolicy,'type'=>$this->mtPolicy[0]['type']]);
                if(!($res && isset($res['errno']) && $res['errno'] == "5000")) {
                    $mtRes = false;
                    logger($this->mtPolicy[0]['policyCode'].'美团平台上传失败:'.json_encode($this->mtPolicy,JSON_UNESCAPED_UNICODE));
                    logger($this->mtPolicy[0]['policyCode'].'美团平台上传失败原因:'.json_encode($res,JSON_UNESCAPED_UNICODE));
                }

            }

        } catch (\Exception $exception) {

        }

        $msg = '';

        if (!$hbCtripRes) {

            $msg .= '恒博携程包机失败,';
        }

        if (!$mhCtripRes) {

            $msg .= '茂华携程包机失败,';
        }

        if (!$quRes) {

            $msg .= '去哪失败,';
        }

        if (!$fzRes) {

            $msg .= '飞猪失败,';
        }

        if (!$mtRes) {

            $msg .= '飞猪失败,';
        }


        $this->ctripPolicy      = [];
        $this->mhCtripPolicy    = [];
        $this->ctripRulePolicy      = [];
        $this->mhCtripRulePolicy    = [];
        $this->tcPolicy         = [];
        $this->mtPolicy         = [];

        if ($msg) {

            return $msg;
        }

    }

    /**
     * 如果不存在了，下政策
     * @param $param
     * @param $policy
     * @return void
     */
    private function policyDelete($param, $policy){
        //查询是否已经有政策
        $policyUploadInterface = resolve('App\Repositories\Contracts\PolicyUploadInterface');
        $flightExistParam = [
            'depart_city_code'      => $param['depart_city_code'],
            'arrived_city_code'     => $param['arrived_city_code'],
            'depart_at'             => date('Y-m-d',strtotime($param['date'])),
            'flight_code'           => $param['flight_code'],
            'status'                => 1,
            'platform'              => $policy['product_type'],
            'admin_id'              => $policy['admin_id'],
            ['policy_code','like',$policy['policy_code'].'%']
        ];

        $policyUploadInterface->update($flightExistParam,['status'=>-2]);
    }

    /**
     * 判断政策是否存在
     * @param $param
     * @param $cabin
     * @param $policy
     * @return bool
     */
    private function policyExist($param, $cabin, $policy){

        //查询是否已经有政策
        $policyUploadInterface = resolve('App\Repositories\Contracts\PolicyUploadInterface');
        $flightExistParam = [
            'depart_city_code'      => $param['depart_city_code'],
            'arrived_city_code'     => $param['arrived_city_code'],
            'depart_at'             => date('Y-m-d',strtotime($param['date'])),
            'flight_code'           => $param['flight_code'],
            'status'                => 1,
            'platform'              => $policy['product_type'],
            'admin_id'              => $policy['admin_id'],
            ['policy_code','like',$policy['policy_code'].'%']
        ];

        if (!empty($param['share_flight_code'])) {

            $flightExistParam['share_flight_code'] = $param['share_flight_code'];
        }

        $existRes = $policyUploadInterface->index($flightExistParam);
        if ($existRes) {

            if ($policy['update_type'] == 2) {

                if ($existRes['cabin'] != $cabin['cabin_code'] || $existRes['price'] != $cabin['price']) {

                    $policyUploadInterface->update(['id'=>$existRes['id']],['status'=>-2]);
                    return false;
                }

            }

            return true;
        }
        return false;
    }

    /**
     * 差价价格
     * @param $param
     * @param $cabin
     * @param $policy
     * @return int|string
     */
    private function diffPrice($param,$cabin,$policy){


        if (!empty($policy['diff_price'])) {

            foreach ($param['cabins'] as $value){

                if (strpos(' '.$value['source_type'],$policy['diff_price']) && $cabin['cabin_code'] == $value['cabin_code']) {

                    return number_format((($value['price'] - $cabin['price']) * ($policy['diff_percentage']/100)), 1);
                }
            }
        }


        return 0;

    }

    /**
     * 包机
     * @param $param
     * @return mixed
     */
    private function ctripUpload($param,$cabin,$policy,$policyUpload,$diffPrice){

        $item['admin_id']               = $policy['admin_id'];
        $item['Class']                  = 'Y';
        $item['AdvanceDay']             = $policy['last_sale'];
        $item['MaxAdvanceDay']          = $policy['begin_sale'];
        $item['RcID']                   = $param['ctrip_type'] == 1 ? '10114565' : '14096510';
        $item['AirLine']                = isset($param['share_flight_code']) ? substr($param['share_flight_code'],0,2) : $param['hs_code'];
        $item['FlightWay']              = 'S';
        $item['ApplyChild']             = $policy['apply_child'];
        $item['OfficeNo']               = $policy['office'];
        $item['DepartPort']             = $param['depart_city_code'];
        $item['ArrivePort']             = $param['arrived_city_code'];
        $item['EffectDate']             = $policy['depart_at'];
        $item['ExpiryDate']             = $policy['depart_end'];
        $item['IsValid']                = env('POLICY_VALID') ?  'T'  : 'F';
        $item['ProductType']            = $param['product_type'] ;     //需要咨询
        $item['SaledTicketNum']         = '0';      //已买票个数
        //$item['PrintPrice']             = $cabin['price'] + $policy['add_price'];        //票面价
        $item['PrintPrice']               = $cabin['price'] + $diffPrice;
        $item['SalePrice']              = '';   //建议售价
        $item['InventoryType']          = $policy['fix'] == 1 ? 'FAV': 'FIX';    //库存查询模式,FAV-见舱 FIX-定额
        $item['GoEffectDate']           = $param['date'];
        $item['GoExpiryDate']           = $param['date'];
        $item['IsShareFlight']          = isset($param['share_flight_code']) ? 'T' : ($policy['share']  ? 'T' : 'F');
        $item['SaleTimeLimit']          = $policy['sale_time_enable'];
        $item['IDLimit']                = $policy['id_card'] ? 'T' : 'F';
        $item['IDCardList']             = $policy['id_card'] ? [$policy['id_card']] : '';
        $item['zhu_flight_code']        = $param['flight_code'];

        //默认
        $item['IsCompositionPrice']     = 'F';
        $item['IsBooking']              = 'F';

        //退改控制
        $item['FeeBasis']               = $policy['refund'];
        $item['MinFeeExpense']          = 0;
        $item['RefundRateRemarks']      = 0;
        $item['ReroutRateRemarks']      = 0;
        $item['IsEndorse']              = 'F';

        //限定紧张阈值
        $item['IsShortageFilter']       = $policy['filter_nervous'] == 1 ? 'T' : 'F';
        $item['ShortageFilterCount']    = $policy['nervous_value'];


        $item['RuleDetail']             = isset($param['share_flight_code']) ? substr($param['share_flight_code'],2,6) : substr($param['flight_code'],2,6);   //航班号范围

        $item['IATANo']                 = $policy['iata'];
        $item['TicketInventory']        = $policy->cabin_set->isNotEmpty() ? ($policy['cabin_set'][0]['stock'] ?  : '') : $policy['seat_min'];
        $item['GoSubClass']             = isset($param['share_flight_code']) ? 'Z' : $cabin['cabin_code'];
        $item['SubClass']               = isset($param['share_flight_code']) ? 'Z' : $cabin['cabin_code'];
        $item['GoDays']                 = str_replace(',','',$policy['week_enable']);
        //$item['SetPrice']               = $cabin['price'] + $policy['add_price'];
        $item['SetPrice']               = $cabin['price'] + $diffPrice;
        $item['PolicyCode']             = $policy['policy_code'].'_'.$policyUpload['id'];
        if ($policy['pata'] == "1") {
            $item['NeedPATA']               = 'T';
            $item['PataPriceValue']         = $policy['up_float'];
            $item['DownFloatValue']         = $policy['down_float'];
            $item['PataVerifyPriceOption']  = 1;
        }


        /**
         * 竞价空间
         */
        $item['BidType']                = $policy['rule_set'][0]['biding_percentage'] != 0 ? 1 : 0;
        $item['BiddingSpace']           = ceil(($policy['rule_set'][0]['biding_price']  ? $policy['rule_set'][0]['biding_price'] :  $policy['rule_set'][0]['biding_percentage']) + $diffPrice);
        $item['SalePriceMin']           = $policy['rule_set'][0]['freight_min'];
        $item['SalePriceMax']           = $policy['rule_set'][0]['freight_max'];
        return $item;
    }

    /**
     * 上传携程
     * @param $data
     * @return bool
     */
    private function ctripUploadPolicy($data){

        $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
        $res = $specialPolicyInterface->add($data);
        logger('上传恒博携程结果'.json_encode($res,JSON_UNESCAPED_UNICODE));
        if (isset($res['TradeResult']) && isset($res['TradeResult']['Result']) && !empty($res['TradeResult']['Result']['SuccessList'])) {

            return true;
        } else {

            logger('上传携程错误'.json_encode($res,JSON_UNESCAPED_UNICODE));
        }

        return false;
    }

    /**
     * 上传携程
     * @param $data
     * @return bool
     */
    private function mhCtripUploadPolicy($data){

        $specialPolicyInterface = resolve('App\Repositories\Ota\Ctrip\Policy\Contracts\SpecialPolicyInterface');
        $res = $specialPolicyInterface->addMh($data);
        logger('上传恒博携程结果'.json_encode($res,JSON_UNESCAPED_UNICODE));
        if (isset($res['TradeResult']) && isset($res['TradeResult']['Result']) && !empty($res['TradeResult']['Result']['SuccessList'])) {

            return true;
        }

        logger('JD订单茂华平台上传失败原因:'.json_encode($res,JSON_UNESCAPED_UNICODE));

        return false;
    }

    /**
     * 保存政策
     */
    private function saveUploadPolicy($flight,$cabin,$policy) {

        $policyUpload = [
            'admin_id'                  => $policy['admin_id'],
            'airline'                   => $flight['hs_code'],
            'depart_city_code'          => $flight['depart_city_code'],
            'arrived_city_code'         => $flight['arrived_city_code'],
            'flight_code'               => $flight['flight_code'],
            'depart_at'                 => $flight['date'],
            'cabin'                     => $cabin['cabin_code'],
            'price'                     => $cabin['price'],
            'policy_code'               => $policy['policy_code'],
            'platform'                  => $policy['product_type'],
            'seat'                      => $cabin['seat'],
            'status'                    => 1,
        ];

        $policyUploadInterface = resolve('App\Repositories\Contracts\PolicyUploadInterface');
        $res = $policyUploadInterface->add($policyUpload);
        if ($res) {

            $policyUploadInterface->update(['id'=>$res['id']],['policy_code'=>$policy['policy_code'].'_'.$res['id']]);

            return $res;
        }
        return false;
    }


    /**
     * 上传规则运价
     * @param $param
     */
    private function ctripRuleUpload($param,$cabin,$policy,$policyUpload,$diffPrice){

        $item['PolicyCode']         = $policy['policy_code'].'_'.$policyUpload['id'];
        $item['IATANo']             = '08309722';
        $item['AirLine']            = $param['hs_code'];
        $item['SaleEffectDate']     = date('Y-m-d');
        $item['SaleExpiryDate']     = date('Y-m-d');

        $item['PriceRule']          = 12;
        $item['ApplyChild']         = 'T';
        $item['PolicyStatus']       = env('POLICY_VALID') == 1 ? 'NORMAL' : 'INVALID';
        $item['FlightWay']          = 'S';
        $item['IsShortageFilter']   = $policy['filter_nervous'] == 1 ? 'T' : 'F';
        $item['ShortageFilterCount']= $policy['filter_nervous'] == 1 ? $policy['nervous_value'] : 0;
        $item['NeedPata']           = 'T';
        $item['UpFloatPrice']       = 30;
        $item['DownFloatPrice']     = 100;
        $item['AdvanceDay']         = $policy['last_sale'].'-'.$policy['begin_sale'];

        $item['ProductType']        = 1;

        //销售控制
        $item['ControlTime']        = $policy['sale_time_enable'];

        //去程航班
        $item['GoDepartTimeLimit']  = $policy['time_enable'];
        $item['GoDays']             = explode(',',$policy['week_enable']);
        $item['SaleFlightList'][]     = [
            'DPort'         => $param['depart_city_code'],
            'APort'         => $param['arrived_city_code'],
            'FlightFrom'    => substr($param['flight_code'],2,4),
            'FlightTo'      => substr($param['flight_code'],2,4),
        ];
        $item['GoEffectDate']       = $param['date'];
        $item['GoExpiryDate']       = $param['date'];
        $item['SalePriceMin']       = $policy['rule_set'][0]['freight_min'];
        $item['SalePriceMax']       = $policy['rule_set'][0]['freight_max'];

        //确定所上舱位
        $saleCabin[] = $cabin['cabin_code'];
        if (!empty($policy['cabins'])) {
            $enableCabin = explode(',',$policy['cabins']);
            $saleCabin = [];
            foreach ($enableCabin as $sCabin){

                if ($sCabin ==  $cabin['cabin_code']) {

                    break;
                }
                $saleCabin[] = $sCabin;
            }

        }
        $item['TicketRemark'] = implode(',',$saleCabin).','.$cabin['cabin_code'].$cabin['seat'];
        //价格设置
        $item['RulePriceList'][] = [
            'SubClass'          => implode(',',$saleCabin),
            'RcID'              => '10114565',
            'Commision'         => 0,
            'PriceRule'         => 'DirectMinusValue',
            'NumCarryRule'      => 'RoundUnit',
            'InventoryType'     => $policy['fix'] == 1 ? 'FAV' : 'FIX',
            'SubtractPrice'     => intval($policy['rule_set'][0]['rebate_price']),
            'PrintPriceRange'   => intval($cabin['price']).'-9999',
            'BidType'           => $policy['rule_set'][0]['biding_percentage']  > 0 ? 1 : 0,
            'BiddingSpace'      => $policy['rule_set'][0]['biding_percentage']  > 0 ? $policy['rule_set'][0]['biding_percentage'] : intval($policy['rule_set'][0]['biding_price'] + $diffPrice),
        ];

       return $item;
    }

    /**
     * 上传去哪
     * @param $param
     * @return bool
     * @throws \Exception
     */
    private function quUpload($param,$cabin,$policy,$policyUpload,$diffPrice,$type='SINGLE'){

        $item = [];
        $item['actCarrier']         = $param['hs_code'];
        $item['flightcode']         = $param['hs_code'];
        $item['dpt']                = $param['depart_city_code'];
        $item['arr']                = $param['arrived_city_code'];
        $item['flightcondition']    = $param['flight_code'];
        $item['supportCba']         = $policy['apply_child'] == 'T' ? '是' : '否';

        $item['startdate']         = $param['date'];
        $item['enddate']           = $param['date'];

        $item['policycode']        = $policy['policy_code'].'_'.$policyUpload['id'];
        $item['status']            = env('POLICY_VALID') == 1 ?  '有效' : '挂起';
        $item['productMark']       = $policy->product_mark->pluck('product_mark')->toArray();

        $item['type']              = $type ;
        $item['depttimeslot']       = $policy['time_enable'];
        $item['daycondition']       = str_replace(",","",$policy['week_enable']);
        $item['cabin']              = $cabin['cabin_code'];
        $item['saledatestart']      = $policy['rule_at'];
        $item['saledateend']        = $policy['rule_end'];
        $item['cardtype']           = $policy['id_card'] == 'ID' ? 1 : 0;
        /*$item['cabinPriceData']     = $policy['policy_code'] == 'TC-SY打卡普通'? '公布运价' : '公布运价,私有运价,直减运价';
        $item['printsource']        = '组合运价最低价';*/
        $item['cabinPriceData']     = $policy['policy_code'] == 'TC-SY打卡普通'? '公布运价' : '公布运价,私有运价,直减运价';
        $item['printsource']        = '指定票面价';
        //$item['printprice']         = $cabin['price']+$policy['add_price'];
        $item['printprice']         = $cabin['price']+$diffPrice;
        $item['highDemandThreshold'] = $policy['nervous_value'];
        $item['flightNoLimit']       = '适用';
        $item['shared']              = '否';
        $item['needPnr']             = '否';
        $item['needPata']            = $policy['pata'] == '1' ? '是':'否';
        $item['cabinNote']           = '测试';
        $item['earliestBeforeTicket'] = $policy['begin_sale'];
        $item['beforeTicket']        = $policy['last_sale'];
        $item['policyReturnPoint']   = $policy['rule_set'][0]['rebate_percentage'];
        $item['policyReturnPrice']   = intval($policy['rule_set'][0]['rebate_price']) < 0 ? 0 : intval($policy['rule_set'][0]['rebate_price']);
        $item['autoPriceThreshold']  = (intval($policy['rule_set'][0]['biding_price'])  + $diffPrice) < 0 ? 0 : intval($policy['rule_set'][0]['biding_price'])  + $diffPrice;
        //logger('去哪竞价空间：'.$item['autoPriceThreshold']);
        $item['percentPriceThreshold']   = $policy['rule_set'][0]['biding_percentage'];
        $item['lockTime']            = $policy['last_sale_minute'];
        $item['saleTimeSlot']        = $policy['sale_time_enable'];

        //指定票面价不能设置最高票面价
        if($item['printsource']  != '指定票面价'){

            $item['minPrintPrice']       = $policy['rule_set'][0]['freight_min'];
            $item['maxPrintPrice']       = $policy['rule_set'][0]['freight_max'];
        }




        $item['highDemandType'] = '';
        if ($item['highDemandThreshold'] > 0) {

            $item['highDemandType'] = '禁售';
        }


        QnService::QnDataSet($item);
        $item['ext']           = $policy['policy_code'].'_'.$policyUpload['id'];

        return $item;

    }

    /**
     * 上传去哪
     * @param $data
     * @return bool
     */
    private function qnUploadPolicy($data) {

        $quPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
        $res = $quPolicyInterface->add($data);

        if (substr($res,0,1) == "\n") {

            return true;
        }

        logger('HUAPP上传政策-失败'.$res);

        return false;

    }

    /**
     * 上传去哪
     * @param $data
     * @return bool
     */
    private function qnFxUploadPolicy($data) {

        $quPolicyInterface = resolve('App\Repositories\Ota\Qn\Policy\Contracts\QuPolicyInterface');
        $res = $quPolicyInterface->addFenXiao($data);
        if (substr($res,0,1) == "\n") {

            return true;
        }
        logger('HUAPP分销上传政策-失败'.$res);

        return false;

    }

    /**
     * 上传同城
     * @param $param
     */
    private function tcUpload($param,$cabin,$policy,$policyUpload,$diffPrice){

        $item = [];
        $item['airCompany']             = $param['hs_code'];
        $item['startPort']              = $param['depart_city_code'];
        $item['endPort']                = $param['arrived_city_code'];
        $item['flightNoFit']            = 1;
        $item['flightNoList']           = $param['flight_code'];
        $item['startDate']              = $param['date'];
        $item['endDate']                = $param['date'];
        $item['startSellDate']          = $policy['rule_at'];
        $item['endSellDate']            = $policy['rule_end'];
        $item['isValid']                = env('POLICY_VALID') == 1 ? 1 : 0;
        $item['cabinCodeList']          = $cabin['cabin_code'];
        $item['policyCode']             = $policy['policy_code'].'_'.$policyUpload['id'];
        $item['saleWeekSegmentList']    = explode(',',$policy['week_enable']);
        $item['sellType']               = $policy['fix'];
        $item['everydayInventory']      = $policy->cabin_set->isNotEmpty() ? $policy['cabin_set'][0]['stock'] : $policy['seat_min'];
        //$item['fixedTotalPrice']        = $cabin['price'] + $policy['add_price'] ;
        $item['fixedTotalPrice']        = $cabin['price'] + $diffPrice ;
        $item['avEffectiveSaleValue']   = $policy['nervous_value'];
        $item['startSaleDay']           = $policy['begin_sale'];
        $item['endSaleDay']             = $policy['last_sale'];
        $item['weekSegmentList']        = [1,2,3,4,5,6,7];
        $item['reimbursementType']      = !empty($policy->product_mark) ? $policy->product_mark[0]['product_mark'] : 1;
        $item['sellPriceLowerLimit']    = $policy['rule_set'][0]['freight_min'];
        $item['sellPriceUpperLimit']    = $policy['rule_set'][0]['freight_max'];

        //$item['analyzeTicketOfficeNo']  = $policy['office'];

        if ($policy['policy_code'] == 'TC-SY打卡普通') {

            //使用舱位
            $item['valuationType']          = 1;
            $item['actionType']             = 3;
            $item['verifyPriceOffice']      = $policy['office'];
            $item['addSubtractBaseType']    = 2;
            $item['addSubtractMoney']       = 1;
            $item['sameCabinPriceType']     = 1;
            $item['nfdType']                = 1;
            $item['calculationLogic']       = 5;
            $item['farePriceType']          = '1';
            //使用舱位结束
        }/* else if (mb_strpos(' '.$policy['policy_code'],'TC-普通XQ')) {

            //使用舱位
            $item['valuationType']          = 1;
            $item['actionType']             = 3;
            $item['verifyPriceOffice']      = $policy['office'];
            $item['addSubtractBaseType']    = 2;
            $item['addSubtractMoney']       = 1;
            $item['sameCabinPriceType']     = 1;
            $item['nfdType']                = 1;
            $item['calculationLogic']       = 5;
            $item['farePriceType']          = '2';
            //使用舱位结束
        }*/ else {
            //固定价格
            $item['valuationType']          = 2;
            $item['verifyPriceOffice']      = $policy['office'];
            //固定价格结束
        }

        //销售时间限制
        $saleTimeLimit                  = $policy['sale_time_enable'];
        if ($saleTimeLimit) {

            $saleTimeLimitArray = explode('-',$saleTimeLimit);
            $item['startSaleApplyTime']     = substr($saleTimeLimitArray[0],0,2).':'.substr($saleTimeLimitArray[0],2,2);
            $item['endSaleApplyTime']       = substr($saleTimeLimitArray[1],0,2).':'.substr($saleTimeLimitArray[1],2,2);
        } else {
            $item['startSaleApplyTime']     = '00:00';
            $item['endSaleApplyTime']       = '23:59';
        }

        if (!empty($policy['time_enable']) && strpos($policy,'-')) {
            $item['applyTimeRangeSegment'] = '';
             $timeLimit = explode(',',$policy['time_enable']);
             foreach ($timeLimit as $key=>$value) {

                 $item['applyTimeRangeSegment'] .= substr($value,0,2).":".substr($value,2,5).':'.substr($value,7,9).',';
             }
            $item['applyTimeRangeSegment'] = substr($item['applyTimeRangeSegment'],0,strlen($item['applyTimeRangeSegment'])-1);
         }

        $item['adultRebatePercent'] = sprintf('%.1f',$policy['rule_set'][0]['rebate_percentage']);
        $item['adultRebateMoney'] = $policy['rule_set'][0]['rebate_price'];
        $item['officeNo'] = $policy['office'];
        $item['keepMoney'] = ($policy['rule_set'][0]['biding_price'] + $diffPrice) < 0 ? 0 : $policy['rule_set'][0]['biding_price'] + $diffPrice;
        $item['resRuleType'] = $policy['id_card'] == 'ID' ? 2 : 1;
        $item['resCardType'] = $policy['id_card'] == 'ID' ? 11 : '';

        if ($policy['pata'] == '1') {
            $item['isVerifyPrice'] = 1;
            $item['floatPrice']    = $policy['up_float'];
        }


        TcService::TcDataSet($item);

        return $item;
    }

    /**
     * 同程上传数据
     * @param $data
     * @return bool
     */
    private function tcUploadPolicy($data) {

        $tcInterface = resolve('App\Repositories\Ota\Tc\Policy\Contracts\TcPolicyInterface');
        $res = $tcInterface->addSpecial($data);
        if($res && isset($res['success']) && $res['isCompress'] == 0) {

            return true;
        }

        logger('同程失败原因'.$res);


        return false;
    }


    /**
     * 飞猪上传政策
     * @param $param
     * @param $cabin
     * @param $policy
     * @param $policyUpload
     * @return array
     */
    public function fzUpload($param,$cabin,$policy,$policyUpload,$diffPrice){

        $item = [
            "airline"=> substr($param['flight_code'],0,2),
            "arrAirport"=> $param['arrived_city_code'],
            "codeShare"=> 0,
            "codeShareAirline"=> "",
            "createPnr"=> 0,
            "createPnrLimit"=> $policy['nervous_value'],
            "depAirport"=> $param['depart_city_code'],
            "directTransferType"=> 0,
            "fareSource"=> [],
            "flights"=> [
                [
                    "allowFlightNum"=> substr($param['flight_code'],2,4),
                    "allowFlightNum2"=> "",
                    "allowTravelDate"=> [
                        [
                            "end"=> $param['date'],
                            "start"=> $param['date'],
                        ]
                    ],
                    //"allowTravelTime"=> "",
                    "cabin"=> $cabin['cabin_code'],
                    "cabinClass"=> "Y",
                    "dayWeek"=> [],
                    "flightIndex"=> 0,
                    /*"restrictFlightNum"=> "",
                    "restrictFlightNum2"=> "",
                    "restrictTravelDate"=> [
                        [
                            "end"=> "",
                            "start"=> ""
                        ]
                    ]*/
                ]
            ],
            "isWhite"=> 0,
            "memo"=> "",
            "notApplOd"=> [],
            "officeNo"=> "CGO134",
            //"outMainFlight"=> true,
            "pata"=> $policy['pata'] == '1' ? 1 : 0 ,
            "policyCode"=> $policy['policy_code'].'_'.$policyUpload['id'],
            "policySource"=> 2,
            //"farePrice"=>intval($cabin['price']+ $policy['add_price']),
            "farePrice"=>intval($cabin['price']+ $diffPrice),
            "price"=> [
                "biddFee"=>  intval($policy['rule_set'][0]['biding_price'] * 100 +  $diffPrice * 100),
                "biddFeePercent"=> intval($policy['rule_set'][0]['rebate_percentage']) ,
                "commission"=> 0,
                "maxPriceLimit"=> $policy['rule_set'][0]['freight_min'],
                "minPriceLimit"=> $policy['rule_set'][0]['freight_max'],
                "returnPrice"=> 0,
                //"outPrice"=>0,
                //"backPrice"=>0
            ],
            "sale"=> [
                "advanceDay"=> $policy['last_sale']."-".$policy['begin_sale'],
                "goodsMarket"=> [],
                "saleDate"=> [
                    [
                        "end"=> $param['date'],
                        "start"=> date('Y-m-d')
                    ]
                ],
                "saleModeCode"=> 0,
                "saleTime"=> $policy['sale_time_enable'],
                "stayDay"=> "",
                "stayTimeUnit"=> 0,
                "supplyProductCode"=> $policy['platform'] == 50 ? [] : $policy->product_mark->pluck('product_mark')->toArray(),
                "useProductModel"=> $policy['platform'] == 50 ? 0 : 1
            ],
            "status"=> env('POLICY_VALID') == 1 ? 1 : 2,
            "urgentStopSell"=> 1,
            "policyType" => 'T',
        ];

        return $item;
    }


    /**
     * 飞猪上传政策
     * @param $param
     * @param $cabin
     * @param $policy
     * @param $policyUpload
     * @return array
     */
    public function fzUploadCommon($param,$cabin,$policy,$policyUpload,$diffPrice){

        $keepMoney = 0;
        if (mb_strpos(' '.$policy['policy_code'],'TC-普通促销') && $diffPrice > 30){

            $keepMoney = ($diffPrice - 30) * -1;

            $diffPrice = 30;
        }


        $item = [
            "airline"=> substr($param['flight_code'],0,2),
            "arrAirport"=> $param['arrived_city_code'],
            "codeShare" => 0,
            "codeShareAirline" => "",
            "createPnr" => 0,
            "createPnrLimit"=> $policy['nervous_value'],
            "depAirport"=> $param['depart_city_code'],
            "directTransferType" => 0,
            "fareSource" => [],
            "flights" => [
                [
                    "allowFlightNum"=> substr($param['flight_code'],2,4),
                    "allowFlightNum2" => "",
                    "allowTravelDate" => [
                        [
                            "end"=> $param['date'],
                            "start"=> $param['date'],
                        ]
                    ],
                    //"allowTravelTime"=> "",
                    "cabin"=> $cabin['cabin_code'],
                    "cabinClass" => "Y",
                    "dayWeek" => [],
                    "flightIndex" => 0,
                    /*"restrictFlightNum"=> "",
                    "restrictFlightNum2"=> "",
                    "restrictTravelDate"=> [
                        [
                            "end"=> "",
                            "start"=> ""
                        ]
                    ]*/
                ]
            ],
            "isWhite" => 0,
            "memo" => "",
            "notApplOd" => [],
            "officeNo" => "CGO134",
            //"outMainFlight"=> true,
            "pata"=> $policy['pata'] == '1' ? 1 : 0 ,
            "policyCode"=> $policy['policy_code'].'_'.$policyUpload['id'],
            "policySource" => 2,
            "farePrice" => 0,
            "price" => [
                "biddFee"=>  intval($policy['rule_set'][0]['biding_price'] * 100 +  $diffPrice * 100) < 0 ? 0 : intval($policy['rule_set'][0]['biding_price'] * 100 +  $diffPrice * 100),
                "biddFeePercent"=> intval($policy['rule_set'][0]['rebate_percentage']) ,
                "commission" => 0,
                "maxPriceLimit"=> $policy['rule_set'][0]['freight_max'],
                "minPriceLimit"=> $policy['rule_set'][0]['freight_min'],
                "returnPrice" => intval($keepMoney * 100),
                //"outPrice"=>0,
                //"backPrice"=>0
            ],
            "sale" => [
                "advanceDay"=> $policy['last_sale']."-".$policy['begin_sale'],
                "goodsMarket" => [],
                "saleDate" => [
                    [
                        "end"=> $param['date'],
                        "start"=> date('Y-m-d')
                    ]
                ],
                "saleModeCode" => 0,
                "saleTime"=> $policy['sale_time_enable'],
                "stayDay" => "",
                "stayTimeUnit" => 0,
                "supplyProductCode"=> $policy['platform'] == 52 ? [] : $policy->product_mark->pluck('product_mark')->toArray(),
                "useProductModel"=> $policy['platform'] == 52 ? 0 : 1
            ],
            "status" => env('POLICY_VALID') == 1 ? 1 : 2,
            "urgentStopSell" => 1,
            "policyType" => 'P',
        ];

        return $item;
    }


    /**
     * 美团政策上传
     * @param $param
     * @param $cabin
     * @param $policy
     * @param $policyUpload
     * @return mixed
     */
    private function mtUpload($param,$cabin,$policy,$policyUpload,$diffPrice,$type = 'PREPAY') {

        $item = [];
        $item['policyCode']                   = $policy['policy_code'].'_'.$policyUpload['id'];
        $item['flightcode']                   = $param['hs_code'];
        $item['dpt']                          = $param['depart_city_code'];
        $item['arr']                          = $param['arrived_city_code'];
        $item['startdate']                    = $param['date'];
        $item['enddate']                      = $param['date'];
        $item['cabin']                        = $cabin['cabin_code'];
        $item['startdate_ticket']             = date('Y-m-d');
        $item['enddate_ticket']               = $param['date'];
        $item['flightNumLimit']               = '适用';
        $item['productType']                  = implode(',',$policy->product_mark->pluck('product_mark')->toArray());
        $item['flightcondition']              = $param['flight_code'];
        $item['discountType']                 = "1";
        //$item['discountValue']                = $cabin['price']+ $policy['add_price'] ;
        $item['discountValue']                = $cabin['price']+ $diffPrice ;
        $item['type']                         = $type;
        $item['allCabin']                     = $policy->cabin_set->isNotEmpty() ? ($policy['cabin_set'][0]['stock'] ?  : '') : $policy['seat_min'];
        $item['beforeValidDay']               = 1;
        $item['earliestBeforeValidDay']       = 365;
        $item['saleTimeSlot']                 = $policy['sale_time_enable'];
        $item['discountThreshhold']           = intval($policy['rule_set'][0]['biding_price'] + $diffPrice);
        $item['pnrStrategy']                  = 2;
        $item['tightSeatCount']               = $policy['nervous_value'];
        $item['returnPointCalMode']           = 3;
        $item['pata']                         = $policy['pata'] == '1' ? 1 : 0 ;
        $item['ticketPriceRange']             = $policy['rule_set'][0]['freight_min'].'-'.$policy['rule_set'][0]['freight_max'];
        return $item;
    }

}